package MTRequest;

import java.sql.ResultSet;

import MTProxyServer.MTConstant;
import MTProxyServer.MessageCentre;
import SQLManager.SQLManager;

public class MTServerCreateEvent extends MTRequest{
	
	public MTServerCreateEvent( MessageCentre aMSGCenter )
	{
		super( aMSGCenter );
		this.mRequestState = MTConstant.MT_REQ_NO_READY;
	}
	
	protected void UpdateRequestState( int aPeerState )
	{
		if( MTConstant.MT_REQ_CCE_SEND_EVENT_INFO == aPeerState ){
			this.mRequestState = MTConstant.MT_REQ_SCE_CREATE_EVENT;
		}
	}
	
	protected void ProcessReqest( int aPeerState, String peerRawData )
	{
		switch( aPeerState ){
			case MTConstant.MT_REQ_CCE_SEND_EVENT_INFO:{
				
				this.mReceivedFromPeerRawData.add( peerRawData );
				
				//Remark: Don't Send Product List information.
				// Assign one Event ID
				
				System.out.println( "EventInfo:" + peerRawData.replace( MTConstant.MT_REQ_RAW_DATA_SEPARATER, ',') );
				String eventID = CreateNewEvent( peerRawData );
				
				// if( result != null )
				// update the event Info on Server side;
				// update the Update Table, Synchronize Table
				
				this.mSendingToPeerRawData.add( eventID );
				
				break;
			}
		}
	}
	
	public void SendRequest()
	{
		String request = "" + MTConstant.MT_REQID_CREATE_EVENT + MTConstant.MT_REQ_ITEM_SEPARATER + 
		this.mRequestState + MTConstant.MT_REQ_ITEM_SEPARATER;
		switch( this.mRequestState ){
			case MTConstant.MT_REQ_SCE_CREATE_EVENT:{
				request += this.mSendingToPeerRawData.get( 0 );
				break;
			}
		}
		this.SendMSG(request);		
		
		if( MTConstant.MT_REQ_SCE_CREATE_EVENT == this.mRequestState ){
			this.Finish();
		}
	}
	
	/**
	 * 
	 * @return EventID
	 */
	private String CreateNewEvent( String aEventInfo )
	{	
		String eventID = "";
		
		// Master, Title, Contact Member, Location
		String [] eventInfoItem = aEventInfo.split( "" + MTConstant.MT_REQ_RAW_DATA_SEPARATER );
		
		SQLManager sqlManager = SQLManager.GetInstance();
		
		try{
			sqlManager.ConnectSQL();
			
			String query = String.format(
					"INSERT INTO " + MTConstant.MT_SQL_DB + ".EventTable ( Master, Title, ContactMember, Location ) " +
					"VALUES ( %s )", 
					aEventInfo.replace( MTConstant.MT_REQ_RAW_DATA_SEPARATER, ',') );
			
			sqlManager.UpdateTable( query );
			
			query = "SELECT LAST_INSERT_ID()";
			ResultSet rs = sqlManager.Query( query, "" );
			
			if( rs.next() ){
				eventID = rs.getString( 1 );
			}
			
			// Create Event's Synchonize Table and ProductList
			query = String.format(  
					"CREATE TABLE " + MTConstant.MT_SQL_DB + ".SynchronizeTable_%s ( " +
					"UserID INT NOT NULL ," +
					"IsUpdated TINYINT(1) ZEROFILL NULL," +
					"UpdateCount INT NULL," +
					"PRIMARY KEY ( UserID ) )"
					, eventID );
			sqlManager.UpdateTable( query );
			
			query = String.format(
				"CREATE  TABLE " + MTConstant.MT_SQL_DB + ".ProductList_%s (" +
					  "ProductID INT NOT NULL AUTO_INCREMENT ," +
					  "Owner INT NULL ," +
					  "ProductName VARCHAR(45) NULL ," +
					  "Description VARCHAR(255) NULL ," +
					  "Price FLOAT NULL ," +
					  "Quality FLOAT NULL ," +
					  "Image VARCHAR(45) NULL ," +
					  "PRIMARY KEY (ProductID) ," +
					  "UNIQUE INDEX ProductID_UNIQUE (ProductID ASC) )"
					  , eventID );
			sqlManager.UpdateTable( query );
			
			String contactMemberStr = eventInfoItem[ 2 ].substring( 1, eventInfoItem[ 2 ].length() - 1 );
			String [] contactMembers = contactMemberStr.split( " " );
			
			for( int i = 0 ; i < contactMembers.length; ++i ){
				System.out.println( "Contact Member " + i + " " + contactMembers[i] );
			}
			// Update User's Update Table
			
			for( int i = 1; i < contactMembers.length; ++i ){
				String userDB = "User_" + contactMembers[i];
				System.out.println( "UerDB:" + userDB );
				
				query = String.format(
						"INSERT INTO %s.%s_UpdateTable ( EventID, Master, IsFinished, UpdateType, TimeCreated ) VALUES ( %s, %s, %b, %d, NOW() )", 
						MTConstant.MT_SQL_DB,
						userDB,
						eventID,
						contactMembers[0],
						false,
						MTConstant.MT_ID_UPT_CREATE_TABLE );
				System.out.println( query );
				sqlManager.UpdateTable( query );
			}
			
			
			// Update SynchroizeTable
			for( int i = 0 ; i < contactMembers.length ; ++i ){
				
				boolean isUpdated = true;
				int count = 0;
				
				// If not a matser
				if( !eventInfoItem[0].matches( contactMembers[i] ) ){
					isUpdated = false;
					count = 1;
				}
				query = String.format(
						"INSERT INTO " + MTConstant.MT_SQL_DB + ".SynchronizeTable_%s ( UserID, IsUpdated, UpdateCount ) VALUES ( %s, %b, %d )", 
						eventID,
						contactMembers[i],
						isUpdated,
						count );
				sqlManager.UpdateTable( query );
			}
			
			sqlManager.Close();
		}
		catch( Exception e ){
			e.printStackTrace();
		}
		
		return eventID;
	}

}
